'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 进入战斗
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var _ = require('lodash');
var Code = require('../../../consts/code');
var moduleType = require('../../../consts/moduleType');
var operationType = require('../../../consts/operationType');
var surviveData = require('../../../libs/war/surviveData');
var constantUtil = require('../../../util/constantUtil');
var PlayerManager = require('../../../libs/playerManager');
var dealRewardService = require('../../../services/dealRewardService');
var surviveService = require('../../../services/surviveService');
var rewardService = require('../../../services/rewardService');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 进入副本协议
 * 要给客户端下发的数据:
 * 1.敌方的建筑
 * 2.敌方的英雄,小兵
 * 3.我方的英雄,小兵
 */
Handler.prototype.wave = function (msg, session, next) {
    var role_id = session.uid;
    var wave_num = msg.wave_num;

    var reward_list = [];
    var def_data;
    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'bag', 'soldier', 'survive', 'task', 'achieve', 'daily_task', 'build', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var survive_model = player_manager.survive;
                var role_model = player_manager.role;

                var current_wave = survive_model.passCurrentWave();

                reward_list = surviveService.getRewardList(role_model.job_type, current_wave);
                if (_.size(reward_list) !== 0) {
                    survive_model.addRewardRecord(current_wave, reward_list);
                }

                rewardService.addRewardListToRole(player_manager, reward_list);

                def_data = _getDef(current_wave + 1);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    def: def_data,
                    reward_list: dealRewardService.dealRewardList(reward_list)
                }
            });
        }
    );
};

/**
 * 获取防守方数据
 * @return {[type]} [description]
 */
var _getDef = function (wave_num) {
    return surviveData.getDataNoSoldier(wave_num);
};
